<script setup>
import { getCurrentInstance, onMounted, reactive, ref } from 'vue'
import * as echars from 'echarts'

const getImageUrl = (user) => {
  return new URL(`../assets/images/${user}.jpg`, import.meta.url).href
}
const tableData = ref([])
const tableLabel = ref({
  name: '商品',
  todayBuy: '今日购买',
  monthBuy: '本月购买',
  totalBuy: '总购买',
})
const CountData = ref([])
const observer = ref()
//这个是折线图和柱状图 两个图表共用的公共配置
const xOptions = reactive({
  // 图例文字颜色
  textStyle: {
    color: '#333',
  },
  legend: {},
  grid: {
    left: '20%',
  },
  // 提示框
  tooltip: {
    trigger: 'axis',
  },
  xAxis: {
    type: 'category', // 类目轴
    data: [],
    axisLine: {
      lineStyle: {
        color: '#17b3a3',
      },
    },
    axisLabel: {
      interval: 0,
      color: '#333',
    },
  },
  yAxis: [
    {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#17b3a3',
        },
      },
    },
  ],
  color: ['#2ec7c9', '#b6a2de', '#5ab1ef', '#ffb980', '#d87a80', '#8d98b3'],
  series: [],
})
// 饼状图
const pieOptions = reactive({
  tooltip: {
    trigger: 'item',
  },
  legend: {},
  color: ['#0f78f4', '#dd536b', '#9462e5', '#a6a6a6', '#e1bb22', '#39c362', '#3ed1cf'],
  series: [],
})

const { proxy } = getCurrentInstance()
// 获取左侧表单数据
const getTableData = async () => {
  const data = await proxy.$api.getTableData()
  tableData.value = data.tableData
}
// 获取右侧头部数据
const getCountData = async () => {
  CountData.value = await proxy.$api.getCountData()
}
// 右侧三个echarts图表 // 刷新页面重新获取
const getChartData = async () => {
  const { orderData, userData, videoData } = await proxy.$api.getChartData()
  //对第一个折线图进行X轴和series赋值
  xOptions.xAxis.data = orderData.date
  xOptions.series = Object.keys(orderData.data[0]).map((val) => ({
    name: val,
    data: orderData.data.map((item) => item[val]),
    type: 'line',
  }))
  const oneEchar = echars.init(proxy.$refs['echart'])
  oneEchar.setOption(xOptions)
  // 对第二个柱形图进行渲染
  xOptions.xAxis.data = userData.map((item) => item.date)
  xOptions.series = [
    {
      name: '新增用户',
      data: userData.map((item) => item.new),
      type: 'bar',
    },
    {
      name: '活跃用户',
      data: userData.map((item) => item.active),
      type: 'bar',
    },
  ]
  const twoEchar = echars.init(proxy.$refs['userEchart'])
  twoEchar.setOption(xOptions)
  // 第三个饼状图
  pieOptions.series = [
    {
      type: 'pie',
      data: videoData,
    },
  ]
  const threeEchar = echars.init(proxy.$refs['videoEchart'])
  threeEchar.setOption(pieOptions)
  //监听页面变化，页面大小改变图表也完整显示
  // ResizeObserver如果监听容器大小发生变化，会执行回调函数
  observer.value = new ResizeObserver(() => {
    oneEchar.resize()
    twoEchar.resize()
    threeEchar.resize()
  })
  //容器存在
  if (proxy.$refs['echart']) {
    observer.value.observe(proxy.$refs['echart'])
  }
}
onMounted(() => {
  getTableData()
  getCountData()
  getChartData()
})
//一般不写在组件文件里，会对axios进行二次封装（request.js）和统一管理api(api.js)
// axios({
//     url:'/api/home/getTableData',
//     method:'get'
// }).then(res=>{
//     //制造假数据，把交互请求流程，根据接口文档跑通，使用mock拦截请求
//     if(res.data.code === 200){
//         tableData.value = res.data.data.tableData;
//     }
// })
</script>

<template>
  <el-row :gutter="20" class="home">
    <!-- 左侧 -->
    <el-col :span="8" style="margin-top: 20px">
      <!-- shadow="hover"鼠标放上有阴影 -->
      <el-card shadow="hover">
        <div class="user">
          <img :src="getImageUrl('user')" alt="" class="user" />
          <div class="user-info">
            <p class="user-info-admin">wj</p>
            <p class="user-info-p">超级管理员</p>
          </div>
        </div>
        <div class="login-info">
          <p>上次登录时间：<span>2025-06-09</span></p>
          <p>上次登录地点：<span>东莞</span></p>
        </div>
      </el-card>
      <!-- 左侧卡片 -->
      <el-card class="user-table" shadow="hover">
        <el-table :data="tableData">
          <el-table-column v-for="(val, key) in tableLabel" :key="key" :label="val" :prop="key">
          </el-table-column>
        </el-table>
      </el-card>
    </el-col>
    <!-- 右侧 -->
    <el-col :span="16" style="margin-top: 20px">
      <!-- 右侧头部卡片 -->
      <div class="num">
        <el-card
          v-for="item in CountData"
          :key="item.name"
          :body-style="{ display: 'flex', padding: 0 }"
        >
          <component :is="item.icon" :style="{ background: item.color }" class="icons"></component>
          <div class="detail">
            <p class="num">￥{{ item.value }}</p>
            <p class="txt">￥{{ item.name }}</p>
          </div>
        </el-card>
      </div>
      <!-- 右侧三个echarts图表 第一个-->
      <el-card class="top-echart">
        <div ref="echart" style="height: 280px"></div>
      </el-card>
      <!-- 第二,三个 -->
      <div class="graph">
        <el-card>
          <div ref="userEchart" style="height: 240px"></div>
        </el-card>
        <el-card>
          <div ref="videoEchart" style="height: 240px"></div>
        </el-card>
      </div>
    </el-col>
  </el-row>
</template>

<style lang="less" scoped>
.home {
  height: 100%;
  //隐藏溢出内容，不显示滚动条
  overflow: hidden;
  padding-top: 0;
  overflow-y: scroll;

  .user {
    display: flex;
    align-items: center;
    border-bottom: 1px solid #ccc;
    margin-bottom: 20px;

    img {
      width: 150px;
      height: 150px;
      border-radius: 50%;
      margin-right: 40px;
    }

    .user-info {
      p {
        line-height: 40px;
      }

      .user-info-admin {
        font-size: 35px;
      }

      .user-info-p {
        color: #999;
      }
    }
  }

  .login-info {
    p {
      line-height: 30px;
      font-size: 14px;
      color: #999;
    }

    span {
      color: #666;
    }
  }

  .user-table {
    margin-top: 20px;
  }

  .num {
    display: flex;
    // 控制 Flex 容器中的子元素（弹性项）是否换行显示。
    flex-wrap: wrap;
    // 控制 主轴（main axis）上的对齐方式。
    // space-between:左右两端对齐，中间间距自动分配
    justify-content: space-between;

    .el-card {
      width: 32%;
      margin-bottom: 20px;
    }

    .icons {
      width: 80px;
      height: 80px;
      font-size: 30px;
      text-align: center;
      line-height: 80px;
      color: #fff;
    }

    .detail {
      margin-left: 15px;
      display: flex;
      flex-direction: column;
      justify-content: center;

      .num {
        font-size: 30px;
        margin-bottom: 10px;
      }

      .txt {
        font-size: 15px;
        text-align: center;
        color: #999;
      }
    }
  }

  .graph {
    display: flex;
    justify-content: space-between;
    margin-top: 20px;

    .el-card {
      width: 48%;
    }
  }
}
</style>
